﻿
// <copyright file="AbstractReaderWriterAtomicOperationSupported.cs" company="Subhadra Software Solutions">
//   
// </copyright>
// <summary>
//   The AbstractReaderWriterAtomicOperationSupported class.
// </summary>


namespace SubhadraSolutions.Sharp.Utils.Threading
{
    using System;
    using System.Threading;

    using SubhadraSolutions.Sharp.Utils.Validation;

    /// <summary>
    /// The AbstractReaderWriterAtomicOperationSupported class.
    /// </summary>
    public abstract class AbstractReaderWriterAtomicOperationSupported : AbstractDisposable, IAtomicOperationSupported
    {
        /// <summary>
        /// The reader writer lock slim
        /// </summary>
        private readonly ReaderWriterLockSlim readerWriterLockSlim = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

        /// <summary>
        /// Gets the lock slim.
        /// </summary>
        /// <value>
        /// The lock slim.
        /// </value>
        protected ReaderWriterLockSlim LockSlim
        {
            get
            {
                return this.readerWriterLockSlim;
            }
        }

        /// <summary>
        /// Performs the atomic operation.
        /// </summary>
        /// <param name="action">
        /// The action.
        /// </param>
        public void PerformAtomicOperation(Action action)
        {
            Guard.ArgumentNotNull(action, "action");
            try
            {
                this.LockSlim.EnterWriteLock();
                action();
            }
            finally
            {
                this.LockSlim.ExitWriteLock();
            }
        }

        /// <summary>
        /// The dispose.
        /// </summary>
        /// <param name="disposing">
        /// The disposing.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            this.LockSlim.Dispose();
        }
    }
}
